import {Form, Modal, Row, Col, Input, Select, InputNumber, TreeSelect} from 'antd';
import {useEffect} from 'react';
import {connect} from 'umi';
import {getAllChildList, getAllParentList} from '@/utils/utils';
import styles from '../styles.less';

const DataForm = (props) => {
  const {dispatch, submitting, menuTree} = props;
  const {dataForm, setDataForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();

  /* 获取菜单列表 */
  useEffect(() => {
    dispatch({
      type: 'SystemCommon/getMenus',
      payload: {status: 1},
    });
  }, [dispatch]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({status: 1, orderby: 0});
    }
    if (dataForm && dataForm.data) {
      let menuIds = dataForm.data.menuIds.map(id => {
        let obj = {value: id};
        menuTree.forEach(item => {
          if (id === item.id) {
            obj.label = item.menuName;
          }
        });
        return obj;
      });
      form.setFieldsValue({...dataForm.data, menuIds});
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });
      if (values.menuIds) {
        values.menuIds = values.menuIds.map(d => d.value);
      }
      dispatch({
        type: values.id ? 'PSystemRole/edit' : 'PSystemRole/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
  }

  /* 监听角色菜单 */
  function onMenuChg(value, label, extra) {
    let menuIds;
    if (extra.checked) {  // 节点选中
      menuIds = value.map(d => d.value);
      menuIds = [...menuIds,
        ...getAllChildList(menuTree, extra.triggerValue),
        ...getAllParentList(menuTree, extra.triggerValue),
      ];
    } else {  // 节点取消选中
      menuIds = form.getFieldValue('menuIds') || [];
      menuIds = menuIds.map(d => d.value);
      let exclude = [extra.triggerValue, ...getAllChildList(menuTree, extra.triggerValue)];
      menuIds = menuIds.filter(d => exclude.findIndex(id => id === d) < 0);
    }
    // 去重
    menuIds = [...new Set(menuIds)];
    // 赋值
    menuIds = menuIds.map(id => {
      let obj = {value: id};
      menuTree.forEach(item => {
        if (id === item.id) {
          obj.label = item.menuName;
        }
      });
      return obj;
    });
    form.setFieldsValue({menuIds});
  }

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={600}
      className={styles.myModal}
    >
      <Form layout='horizontal' labelCol={{span: 5}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='roleName' label='角色名称'
              rules={[
                {required: true, message: '角色名称不能为空'},
              ]}>
              <Input placeholder='请输入角色名称'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='rolePermission' label='角色权限'
              rules={[
                {required: true, message: '角色权限不能为空'},
              ]}>
              <Input placeholder='请输入角色权限'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='orderby' label='排序属性'
              rules={[
                {required: true, message: '排序属性不能为空'},
              ]}>
              <InputNumber style={{width: '100%'}} placeholder='请输入排序属性'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='menuIds' label='角色菜单'
              rules={[
                {required: false, message: '角色菜单不能为空'},
              ]}>
              <TreeSelect
                placeholder='请选择角色菜单'
                treeData={menuTree}
                treeCheckable={true}
                showCheckedStrategy={TreeSelect.SHOW_ALL}
                maxTagCount={2}
                treeCheckStrictly
                onChange={onMenuChg}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='remark' label='备注信息'
              rules={[
                {required: false, message: '备注信息不能为空'},
              ]}
            >
              <Input.TextArea rows={3} placeholder='请输入备注信息'/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};


export default connect(({loading, SystemCommon}) => {
  return {
    submitting: loading.effects['PSystemRole/add'] || loading.effects['PSystemRole/edit'],
    menuTree: SystemCommon.menuTree,
  };
})(DataForm);

